package com.xebest.web.controller.finance;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xebest.api.dto.SendMonitorDTO;
import com.xebest.api.fin.dto.*;
import com.xebest.api.fin.service.XeSysFinPayBillRestApiService;
import com.xebest.api.util.MonitorUtil;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.base.dto.BaseResponseDTO;
import com.xebest.common.base.pagedto.XePageDto;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.RequestUtil;
import com.xebest.constant.XeConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.XeVenImportExcelUtil;
import com.xebest.util.msg.XeVenFinaceMsg;
import com.xebest.web.form.XeVenFinPurchPayForm;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenFinPrepayBillService;
import com.xebest.web.service.XeVenFinPurchPayReadService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenFinPurchPayView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 付款单
 *
 * @author 赵盼飞
 */
@RestController
@RequestMapping("finPurchPay")
public class XeVenFinPurchPayController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenFinPurchPayController.class);//日志记录类

    /**
     * 财务付款单操作service
     */
    @Autowired
    private XeVenFinPurchPayReadService xeVenFinPurchPayReadService;
    /**
     * 财务付款单二方包service
     */
    @Autowired
    private XeSysFinPayBillRestApiService xeSysFinPayBillRestApiService;

    @Autowired
    private XeVenFinPrepayBillService xeVenFinPrepayBillService;//预付单业务

    @Value("${usercode.erp.pay}")
    private String laUsercode;

    /**
     * 查询付款单列表
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryFinPurchPayList")
    public BaseResponse queryXeVenFinPurchPayFormList(@RequestBody XeVenFinPurchPayForm form) {

        log.info("查询付款单列表--->参数：{}", JSON.toJSONString(form));
        try {
            XePageInfo<XeVenFinPurchPayView> xePageInfo;
            PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
            //1.获取userCode
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            Map<String, Object> map = new HashMap<String, Object>();
            form.setUserCode(userInfo.getUserCode());
            //2.查询列表数据
            List<XeVenFinPurchPayView> finPurchPayList = this.xeVenFinPurchPayReadService.queryXeVenFinPurchPayFormList(form);
            for (XeVenFinPurchPayView finPurchPay : finPurchPayList) {
                if (finPurchPay.getVenType() == null) {
                    finPurchPay.setVenType(userInfo.getVenType() + "");
                }
            }

            xePageInfo = new XePageInfo<XeVenFinPurchPayView>(finPurchPayList);
            //3.返回分页信息
            map.put("finPurchPayList", finPurchPayList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询付款单列表接口异常：{}", e);
            return sendAjaxError();
        }

    }


    /**
     * 查询供货商名称
     *
     * @author 赵盼飞
     */
    @RequestMapping("querySupNameList")
    public BaseResponse querySupNameList(@RequestBody XeVenFinPurchPayForm form) {

        try {
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            List<Map<String, Object>> supNameList = this.xeVenFinPurchPayReadService.querysupNameList(userInfo.getUserCode());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("supNameList", supNameList);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询供货商名称接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 查询付款单商品信息
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryFinPurchPayDetail")
    public BaseResponse queryFinPurchPayDetail(@RequestBody @Validated XeVenFinPurchPayForm form,
                                               BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("查询付款单商品信息：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendRemoteAjaxError(fieldError.getDefaultMessage());
        }
        try {
            //1.获取userCode
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            Map<String, Object> map = new HashMap<String, Object>();
            form.setUserCode(userInfo.getUserCode());
            //2.查询列表数据
            List<XeVenFinPurchPayView> finPurchPayDetail = this.xeVenFinPurchPayReadService.queryFinPurchPayDetail(form);
            //3.返回分页信息
            map.put("finPurchPayDetail", finPurchPayDetail);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询付款单商品信息接口异常：{}", e);
            return sendAjaxError();
        }

    }


    /**
     * 发起结算
     *
     * @author 赵盼飞
     */
    @RequestMapping("launchSettlement")
    public BaseResponse launchSettlement(@RequestBody XeVenFinPurchPayForm form) {
        log.info("发起结算参数：" + JSON.toJSONString(form));
        // 获取spanId
        String spanId = getSpanId();
        //1.获取userCode
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        String failSettleCode = "";
        String failMsg = "";
        try {
            //1.验证参数
            if (form.getPsettleCodeArr().length <= 0 || form.getSupplierCodeArr().length <= 0) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            log.info("配置商户code值：-------->" + laUsercode);
            if (!StringUtils.isEmpty(laUsercode)) {
                if (!userInfo.getUserCode().equals(laUsercode)) {
                    return sendAjaxError(XeVenFinaceMsg.SAVE_LAUNCHSETTLEMENT_USERCODE_NO);
                }
            }
            form.setPsettleStatus(1);
            form.setSupplierName(null);
            for (String supCode : form.getSupplierCodeArr()) {
                XeSysFinPayBillRequestDTO payBillDTO = new XeSysFinPayBillRequestDTO();
                payBillDTO.setUserCode(userInfo.getUserCode());
                payBillDTO.setPbType(XeConstans._XE_ONE);
                //本期实付金额
                payBillDTO.setActPayAmount(new BigDecimal("0"));
                payBillDTO.setUnPayAmount(new BigDecimal("0"));
                payBillDTO.setPurchSettleWay(XeConstans._XE_ONE);
                payBillDTO.setSupplierCode(supCode);
                //单号信息
                List<XeSysFinPayBillOrderRequestDTO> list = new ArrayList<XeSysFinPayBillOrderRequestDTO>();
                //3.根据付款单号查询明细需要的数据
                Map<String, Object> paraDetailMap = new HashMap<String, Object>();
                paraDetailMap.put("userCode", userInfo.getUserCode());
                paraDetailMap.put("settleCodeArr", form.getPsettleCodeArr());
                paraDetailMap.put("supCode", supCode);
                List<Map<String, Object>> sysFinPayBillDetails = this.xeVenFinPurchPayReadService.queryXeSysFinPayBillDetailList(paraDetailMap);
                if (null != sysFinPayBillDetails && sysFinPayBillDetails.size() > 0) {
                    List<XeSysFinPayBillDetailRequestDTO> detailList = new ArrayList<XeSysFinPayBillDetailRequestDTO>();
                    XeSysFinPayBillDetailRequestDTO detailEntity = null;
                    XeSysFinPayBillOrderRequestDTO order = null;
                    //本期应付金额
                    BigDecimal payAmounts = new BigDecimal("0").setScale(2);
                    //毛利合计金额
                    BigDecimal profitAmounts = new BigDecimal("0");
                    //自营供货商编码
                    String supplierCode = null;
                    //自营结算单号
                    String settleCode = null;
                    //开户银行名称
                    String accBank = null;
                    // 开户人银行账号
                    String bankAccCard = null;
                    //开户人账号姓名（企业姓名）
                    String bankAccName = null;
                    //供货商名称
                    String supplierName = null;
                    //发货时间
                    Date maxSendTime = DateUtil.toDate(sysFinPayBillDetails.get(0).get("sendTime") + "");

                    for (Map<String, Object> finpay : sysFinPayBillDetails) {
                        supplierName = finpay.get("supplierName").toString();
                        //明细信息
                        detailEntity = new XeSysFinPayBillDetailRequestDTO();
                        detailEntity.setPaySettleCode(finpay.get("psettleCode").toString());
                        if (!StringUtils.isEmpty(finpay.get("orderId")) && finpay.get("purchType").toString().equals("1")) {
                            detailEntity.setOrderId(finpay.get("orderId").toString());
                        }
                        detailEntity.setPbType(XeConstans._XE_ONE);
                        //取最大发货时间
                        if (DateUtil.toDate(finpay.get("sendTime").toString()).after(maxSendTime)) {
                            maxSendTime = DateUtil.toDate(finpay.get("sendTime").toString());
                        }
                        if (null != finpay.get("sendTime")) {
                            detailEntity.setSendTime(DateUtil.toDate(finpay.get("sendTime").toString()));
                        }
                        detailEntity.setProSku(finpay.get("proSku").toString());
                        if (null != finpay.get("orgCode")) {
                            detailEntity.setProOrgCode(finpay.get("orgCode").toString());
                        }
                        if (null != finpay.get("orgCodeName")) {
                            detailEntity.setProOrgCodeName(finpay.get("orgCodeName").toString());
                        }
                        if (null != finpay.get("proName")) {
                            detailEntity.setProName(finpay.get("proName").toString());
                        }
                        if (null != finpay.get("proNo")) {
                            detailEntity.setProNum(finpay.get("proNo").toString());
                        }
                        if (null != finpay.get("priceType")) {
                            detailEntity.setPricingType(finpay.get("priceType").toString());
                        }
                        if (null != finpay.get("proUnit")) {
                            detailEntity.setProUnit(finpay.get("proUnit").toString());
                        }
                        if (finpay.get("proCostPrice") != null) {
                            //成交单价
                            detailEntity.setProCostPrice(new BigDecimal(finpay.get("proCostPrice").toString()));
                        }
                        //实际发货数量
                        if (null != finpay.get("realSendNum")) {
                            detailEntity.setRealSendNum(new BigDecimal(finpay.get("realSendNum").toString()));
                        }
                        //区域商品单价
                        if (null != finpay.get("proPrice")) {
                            detailEntity.setProPrice(new BigDecimal(finpay.get("proPrice").toString()));
                        }
                        //发货金额
                        if (null != finpay.get("proPayAmount")) {
                            detailEntity.setProPayAmount(new BigDecimal(finpay.get("proPayAmount").toString()));
                        }
                        //实际付款金额
                        if (null != finpay.get("purchAmount")) {
                            detailEntity.setRealPayAmount(new BigDecimal(finpay.get("purchAmount") + "").setScale(2));
                        }
                        //实际付款金额总和
                        if (null != detailEntity.getRealPayAmount()) {
                            payAmounts = payAmounts.add(detailEntity.getRealPayAmount().setScale(2));
                        }
                        if (null != finpay.get("proNum")) {
                            detailEntity.setPurchaseNum(new BigDecimal(finpay.get("proNum") + ""));
                        }
                        if (null != finpay.get("proTotalPrice")) {
                            detailEntity.setProTotalPrice(new BigDecimal(finpay.get("proTotalPrice").toString()));
                        }
                        if (!StringUtils.isEmpty(finpay.get("specValue"))) {
                            detailEntity.setSpecValue(finpay.get("specValue").toString());
                        }

                        if (null != finpay.get("sendAmount") && null != finpay.get("purchAmount")) {
                            detailEntity.setProfitAmount(new BigDecimal(finpay.get("sendAmount") + "")
                                    .subtract(new BigDecimal(finpay.get("purchAmount") + "")));
                        }
                        if (finpay.get("buyPrice") != null) {
                            detailEntity.setPurchPrice(new BigDecimal(finpay.get("buyPrice").toString()));
                        }
                        //毛利总和
                        if (null != detailEntity.getProfitAmount()) {
                            profitAmounts = profitAmounts.add(detailEntity.getProfitAmount());
                        }
                        if (null != finpay.get("differenceRefAmount")) {
                            detailEntity.setRefundAmount(new BigDecimal(finpay.get("differenceRefAmount").toString()));
                        }
                        supplierCode = finpay.get("supplierCode").toString();
                        settleCode = finpay.get("psettleCode").toString();
                        if (null != finpay.get("accBank")) {
                            accBank = finpay.get("accBank").toString();
                        }
                        if (null != finpay.get("bankAccCard")) {
                            bankAccCard = finpay.get("bankAccCard").toString();
                        }
                        if (null != finpay.get("bankAccName")) {
                            bankAccName = finpay.get("bankAccName").toString();
                        }
                        if (!StringUtils.isEmpty(finpay.get("pmtAmount"))) {
                            detailEntity.setPmtAmount(new BigDecimal(finpay.get("pmtAmount").toString()));
                        }
                        //关联表信息
                        order = new XeSysFinPayBillOrderRequestDTO();
                        order.setSettleCode(finpay.get("psettleCode").toString());
                        order.setPbType(XeConstans._XE_ONE);
                        list.add(order);
                        detailList.add(detailEntity);//明细信息
                    }
                    //本期应付金额
                    payBillDTO.setPayAmount(payAmounts);
                    //毛利合计
                    payBillDTO.setProfitAmount(profitAmounts);
                    //本期实付
                    payBillDTO.setActPayAmount(payAmounts);
                    payBillDTO.setSupplierCode(supplierCode);
                    payBillDTO.setAccBank(accBank);
                    payBillDTO.setBankAccCard(bankAccCard);
                    payBillDTO.setBankAccName(bankAccName);
                    payBillDTO.setEndSettleTime(maxSendTime);
                    payBillDTO.setRemark(supplierName);

                    payBillDTO.setPayBillDetailList(detailList);//主表信息
                    payBillDTO.setPayBillOrderList(list);
                    // 初始化链路监控传参：key,request,spanId
                    SendMonitorDTO clientSend = MonitorUtil.monitorUtil.controllerRecv(spanId, userInfo.getUserCode(), JSONObject.toJSONString(payBillDTO));
                    // dto监控：参数：response,spanId
                    MonitorUtil.monitorUtil.controllerSend(spanId, JSONObject.toJSONString(sendAjaxOK()), true);
                    // dto透传traceId
                    payBillDTO.setTraceId(clientSend.getTraceId());
                    // dto透传spanId
                    payBillDTO.setSpanId(spanId);
                    payBillDTO.setKey("savePbillSelf");
                    BaseResponseDTO resDTO = xeSysFinPayBillRestApiService.savePbillSelf(payBillDTO);
                    log.info("供货商编码{},自营发起结算返回结果：{}", supplierCode, JSONObject.toJSONString(resDTO));
                    if (resDTO.getStatus().equals("2000")) {
                        //付款单状态更改为付款中
                        form.setStartSettleDate(DateUtil.getDate(new Date()));
                        form.setSelfSettleCode(settleCode);
                        xeVenFinPurchPayReadService.updateBathFinPurchPayByPsettleCodeArr(form);
                        //添加日志
                        insertFinanceMqLog(ErpLogTypeEnum.erpFinPurLaunchSettlement.getValue(), XeVenImportExcelUtil.arrConversonStr(form.getPsettleCodeArr()),
                                "针对供应商名称为：" + form.getSupplierName() + "，发起结账操作，应付账单号为：" + XeVenImportExcelUtil.arrConversonStr(form.getPsettleCodeArr()));
					/*resState=resDTO.getStatus();
					resMsg=resDTO.getMsg();*/
                    } else {
                        failSettleCode += (" " + settleCode);
                        failMsg = resDTO.getMsg();
                    }
                }
                XeSysFinPayBillRequestDTO lastUnPayDTO = new XeSysFinPayBillRequestDTO();
                lastUnPayDTO.setUserCode(userInfo.getUserCode());
                lastUnPayDTO.setSupplierCode(supCode);
                BaseResponseDTO resDTO = xeSysFinPayBillRestApiService.saveLastUnPbillSelf(lastUnPayDTO);
                //resState = (null != resDTO ? resDTO.getStatus() : "");
                log.info("供货商编码{},自营发起上期未结账结算返回结果：{}", supCode, JSONObject.toJSONString(resDTO));
            }
            if (!failSettleCode.equals("")) {
                failSettleCode += failMsg;
            }
        } catch (Exception e) {
            log.error("发起结算接口异常：{}", e);
            // dto监控：参数：spanId,response,状态:true:正确，false:错误
            MonitorUtil.monitorUtil.controllerSend(spanId, JSONObject.toJSONString(sendAjaxError("发起结算系统异常")), false);
            return sendAjaxError();
        }
        return sendAjaxOK(failSettleCode);
    }


    /**
     * 我的应付账单列表
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryMineFinPurchPayList")
    public BaseResponse queryMineFinPurchPayList(@RequestBody XeSysFinPayBillRequestDTO form, @RequestBody XePageDto xePageDto) {

        try {
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            form.setUserCode(userInfo.getUserCode());
            form.setPbType(1);
            form.setReviewStatus(1);
            form.setConfirmBill(2);
            form.setXePageDto(xePageDto);
            form.setCancelStatus(1);
            //2.掉二方包获取分页数据
            ManagerFinPayBillPageDto rsDto = xeSysFinPayBillRestApiService.listSysFinBkg(form);
            //3.返回分页信息
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("dataList", rsDto.getList());
            paraMap.put("xePageInfo", rsDto.getXePageInfoDto());
            return sendAjaxOK(paraMap);
        } catch (Exception e) {
            log.error("我的应付账单列表接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 我的应付账单明细
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryMineFinPurchPayDetail")
    public BaseResponse queryMineFinPurchPayDetail(@RequestBody XeSysFinPayBillDetailRequestDTO form) {

        try {
            if (StringUtils.isEmpty(form.getPbCode())) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            form.setUserCode(userInfo.getUserCode());
            form.setPbType(1);
            //2.掉二方包获取分页数据
            ManagerFinPayBillDetailPageDTO rsDetailDto = xeSysFinPayBillRestApiService.listFinPayDetail(form);
            //3.返回分页信息
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("dataList", rsDetailDto.getList());
            return sendAjaxOK(paraMap);
        } catch (Exception e) {
            log.error("我的应付账单明细接口异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 我的应付账单显示对应上个账期未结算的订单
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryLastMineFinPurchPayList")
    public BaseResponse queryLastMineFinPurchPayList(@RequestBody XeSysFinPayBillDetailRequestDTO form, @RequestBody XePageDto xePageDto) {

        try {
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            form.setUserCode(userInfo.getUserCode());
            form.setPbType(1);
            form.setXePageDto(xePageDto);
            //2.掉二方包获取分页数据
            ManagerFinPayBillDetailPageDTO rsLastDetailDto = xeSysFinPayBillRestApiService.listUnPayBillDetail(form);
            //3.返回分页信息
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("dataList", rsLastDetailDto.getList());
            paraMap.put("xePageInfo", rsLastDetailDto.getXePageInfoDto());
            return sendAjaxOK(paraMap);
        } catch (Exception e) {
            log.error("显示对应上个账期未结算的订单接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 平台应付账单列表
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryPlatformFinPurchPayList")
    public BaseResponse queryPlatformFinPurchPayList(@RequestBody XeSysFinPayBillRequestDTO form, @RequestBody XePageDto xePageDto) {

        try {
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            form.setUserCode(userInfo.getUserCode());
            form.setPbType(2);
            form.setReviewStatus(1);
            form.setConfirmBill(2);
            form.setCancelStatus(1);
            form.setXePageDto(xePageDto);
            //2.掉二方包获取分页数据
            ManagerFinPayBillPageDto rsDto = xeSysFinPayBillRestApiService.listSysFinBkg(form);
            //3.返回分页信息
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("dataList", rsDto.getList());
            paraMap.put("xePageInfo", rsDto.getXePageInfoDto());
            return sendAjaxOK(paraMap);
        } catch (Exception e) {
            log.error("我的应付账单列表接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 平台应付账单明细
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryPlatformFinPurchPayDetail")
    public BaseResponse queryPlatformFinPurchPayDetail(@RequestBody XeSysFinPayBillDetailRequestDTO form) {

        try {
            if (StringUtils.isEmpty(form.getPbCode())) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            form.setUserCode(userInfo.getUserCode());
            form.setPbType(2);
            //2.掉二方包获取分页数据
            ManagerFinPayBillDetailPageDTO rsDetailDto = xeSysFinPayBillRestApiService.listFinPayDetail(form);
            //3.返回分页信息
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("dataList", rsDetailDto.getList());
            return sendAjaxOK(paraMap);
        } catch (Exception e) {
            log.error("我的应付账单明细接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 平台显示对应上个账期未结算的订单
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryLastPlatformFinPurchPayDetail")
    public BaseResponse queryLastPlatformFinPurchPayDetail(@RequestBody XeSysFinPayBillDetailRequestDTO form, @RequestBody XePageDto xePageDto) {

        try {
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            form.setUserCode(userInfo.getUserCode());
            form.setPbType(2);
            form.setXePageDto(xePageDto);
            //2.掉二方包获取分页数据
            ManagerFinPayBillDetailPageDTO rsLastDetailDto = xeSysFinPayBillRestApiService.listUnPayBillDetail(form);
            //3.返回分页信息
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("dataList", rsLastDetailDto.getList());
            paraMap.put("xePageInfo", rsLastDetailDto.getXePageInfoDto());
            return sendAjaxOK(paraMap);
        } catch (Exception e) {
            log.error("显示对应上个账期未结算的订单接口异常：{}", e);
            return sendAjaxError();
        }

    }


    /**
     * 我的应付账单复核成功
     *
     * @author 赵盼飞
     */
    @RequestMapping("finPurchPayCheckSuccess")
    public BaseResponse finPurchPayCheckSuccess(@RequestBody XeVenFinPurchPayForm form) {

        try {
            if (null == form.getPbCodeArr() || form.getPbCodeArr().length <= 0) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

            for (int i = 0; i < form.getPbCodeArr().length; i++) {
                XeSysFinPayBillRequestDTO pForm = new XeSysFinPayBillRequestDTO();
                pForm.setUserCode(userInfo.getUserCode());
                pForm.setPbCode(form.getPbCodeArr()[i]);
                pForm.setPbType(1);
                pForm.setReviewStatus(2);
                //2.掉二方包获取分页数据
                xeSysFinPayBillRestApiService.reviewPbill(pForm);
                //添加日志
                insertFinanceMqLog(ErpLogTypeEnum.erpFinPurMyCheckSuccess.getValue(), XeVenImportExcelUtil.arrConversonStr(form.getPbCodeArr()),
                        "复核成功，具体内容，供应商：" + form.getSupplierName() + "，应付账单号为：" + XeVenImportExcelUtil.arrConversonStr(form.getPbCodeArr()));
            }
            //3.返回分页信息
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("我的应付账单复核成功接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 我的应付账单复核异常
     *
     * @author 赵盼飞
     */
    @RequestMapping("finPurchPayCheckFail")
    public BaseResponse finPurchPayCheckFail(@RequestBody XeVenFinPurchPayForm pform) {

        try {
            if (null == pform.getPbCodeArr() || pform.getPbCodeArr().length <= 0) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

            for (int i = 0; i < pform.getPbCodeArr().length; i++) {
                XeSysFinPayBillRequestDTO form = new XeSysFinPayBillRequestDTO();
                form.setUserCode(userInfo.getUserCode());
                form.setPbCode(pform.getPbCodeArr()[i]);
                form.setPbType(1);
                form.setPbStatus(1);
                form.setReviewStatus(3);
                form.setConfirmBill(1);
                form.setConfirmDate(new Date());
                //2.掉二方包获取分页数据
                BaseResponseDTO dto = xeSysFinPayBillRestApiService.reviewPbill(form);
                if (null != dto && dto.getStatus().equals("2000")) {
                    String[] bArray = {pform.getPbCodeArr()[i]};
                    //解除自营应付单和预付单绑定关系
                    xeVenFinPrepayBillService.relieveRelationSettlePrepay(userInfo.getLoginName(), bArray);
                }
                //添加日志
                insertFinanceMqLog(ErpLogTypeEnum.erpFinPurMyCheckFail.getValue(), XeVenImportExcelUtil.arrConversonStr(pform.getPbCodeArr()),
                        "复核异常，具体内容，供应商：" + pform.getSupplierName() + "，应付账单号为：" + XeVenImportExcelUtil.arrConversonStr(pform.getPbCodeArr()));
            }
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("我的应付账单复核异常接口异常：{}", e);
            return sendAjaxError();
        }

    }


    /**
     * 平台应付账单复核成功
     *
     * @author 赵盼飞
     */
    @RequestMapping("platformPayCheckSuccess")
    public BaseResponse platformPayCheckSuccess(@RequestBody XeVenFinPurchPayForm pform) {

        try {
            if (null == pform.getPbCodeArr() || pform.getPbCodeArr().length <= 0) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

            for (int i = 0; i < pform.getPbCodeArr().length; i++) {
                XeSysFinPayBillRequestDTO form = new XeSysFinPayBillRequestDTO();
                form.setUserCode(userInfo.getUserCode());
                form.setPbCode(pform.getPbCodeArr()[i]);
                form.setPbType(2);
                form.setReviewStatus(2);
                //2.掉二方包获取分页数据
                xeSysFinPayBillRestApiService.reviewPbill(form);
                //添加日志
                insertFinanceMqLog(ErpLogTypeEnum.erpFinPlatformCheckSuccess.getValue(), XeVenImportExcelUtil.arrConversonStr(pform.getPbCodeArr()),
                        "复核成功，具体内容，供应商：" + pform.getSupplierName() + "，应付账单号为：" + XeVenImportExcelUtil.arrConversonStr(pform.getPbCodeArr()));
            }
            //3.返回分页信息
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("平台应付账单复核成功接口异常：{}", e);
            return sendAjaxError();
        }

    }

    /**
     * 平台应付账单复核异常
     *
     * @author 赵盼飞
     */
    @RequestMapping("platformPayCheckFail")
    public BaseResponse platformPayCheckFail(@RequestBody XeVenFinPurchPayForm pform) {

        try {
            if (null == pform.getPbCodeArr() || pform.getPbCodeArr().length <= 0) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            //1.获取userinfo
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

            for (int i = 0; i < pform.getPbCodeArr().length; i++) {
                XeSysFinPayBillRequestDTO form = new XeSysFinPayBillRequestDTO();
                form.setUserCode(userInfo.getUserCode());
                form.setPbCode(pform.getPbCodeArr()[i]);
                form.setPbType(2);
                form.setPbStatus(1);
                form.setReviewStatus(3);
                form.setConfirmBill(1);
                form.setConfirmDate(new Date());
                //2.掉二方包获取分页数据
                xeSysFinPayBillRestApiService.reviewPbill(form);
                //添加日志
                insertFinanceMqLog(ErpLogTypeEnum.erpFinPlatformCheckFail.getValue(), XeVenImportExcelUtil.arrConversonStr(pform.getPbCodeArr()),
                        "复核异常，具体内容，供应商：" + pform.getSupplierName() + "，应付账单号为：" + XeVenImportExcelUtil.arrConversonStr(pform.getPbCodeArr()));
            }
            //3.返回分页信息
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("平台应付账单复核异常接口异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     * @param logType         操作类型
     * @param key             单号
     * @param operatorContent 操作内容      void
     * @author 赵盼飞
     */
    private void insertFinanceMqLog(String logType, String key, String operatorContent) {
        try {
            String ipAddress = RequestUtil.getClientIpAddress(request);
            if (StringUtils.isEmpty(logType)) {
                logType = ErpLogTypeEnum.erpFinPurchPay.getValue();
            }
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            String userCode = userInfo.getUserCode();
            OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, key, logType, userInfo.getUserName(), operatorContent, userCode);
        } catch (Exception e) {
            log.error("财务相关MQ日志插入失败,logType={},operatorContent={}", logType, operatorContent);
        }
    }

}
  
